package org.freemarker.web.controller;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.ws.RespectBinding;

import org.freemarker.core.model.User;
import org.freemarker.core.service.UserService;
import org.freemarker.web.custom.CustomHttpServlet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;


@Controller
public class LoginController extends CustomHttpServlet {
	 
	/**
	 * 
	 */
	private static final long serialVersionUID = -8634274586744904740L;

	
	@Autowired
	private UserService userService;
	
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		req.getRequestDispatcher("views/login/login.ftl").forward(req, resp);
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
 		String userName = req.getParameter("userName");
		String password = req.getParameter("password");
		
		String dest=req.getHeader("Referer");
		
		if(dest==null || dest.endsWith("login")){
			dest="";
		}else{
			dest= dest.substring(dest.lastIndexOf("/") +1);
		}
		
		boolean valid = userService.validLogin(userName, password);
		if(valid){
			HttpSession session = req.getSession();
            session.setAttribute("user", userName);
			
		}else{
			dest = "views/login/loginFailed.ftl";
			req.getRequestDispatcher(dest).forward(req, res);
		}
		res.sendRedirect(dest);
//		req.getRequestDispatcher(dest)
//		.forward(req, res);
		
	}
}
